import random
import threading

import requests

requests.packages.urllib3.disable_warnings()


class Qmxfxx:
    def __init__(self, auth, shebe):
        self.shebe = shebe
        self.headers = {
            "Host": "qmxfxx.119.gov.cn",
            "Connection": "keep-alive",
            "Authorization": auth,
            "Content-Type": "application/json",
            # "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/20A392 Ariver/1.1.0 AliApp(AP/10.3.0.6100) Nebula WK RVKType(0) AlipayDefined(nt:WWAN,ws:390|780|3.0) AlipayClient/10.3.0.6100 Language/zh-Hans Region/CN NebulaX/1.0.0",
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/20A392 Ariver/1.1.0 AliApp(AP/10.3.0.6100) Nebula WK RVKType(0) AlipayDefined(nt:WWAN,ws:390|780|3.0) AlipayClient/10.3.0.6100 Language/zh-Hans Region/CN NebulaX/1.0.0"
        }
        self.name = self.user()
        print(self.name)
        if not self.name:
            print("token 失效")

    def get_info(self, url):
        res = requests.get(url=url, headers=self.headers, verify=False)
        if res.status_code != 200:
            # print("-----get请求-----")
            # print(url)
            # print(f" 网络请求失败，错误码：{res.status_code}")
            return {}
        return res.json()

    def post_info(self, url, data):
        res = requests.post(url=url, headers=self.headers, json=data, verify=False)
        if res.status_code != 200:
            print("-----post请求-----")
            print(url, data)
            print(f" 网络请求失败，错误码：{res.status_code}")
            return {}
        return res.json()

    # ============================== 视频(20) =================================================
    def vido(self):
        # 多线程获取视频ID
        def get_id(number, data_ls):
            ls = []
            url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/news/content/list?channel=5&offset={number}&limit=10"
            res = self.get_info(url)
            if not res:
                return 0
            for tdict in res["result"]["videoList"]:
                ls.append(tdict["videoId"])
            lock.acquire()
            data_ls += ls
            lock.release()

        # 多线程发送请求
        def send(d_id):
            url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/home/taskScord/completeTask?taskCode=CTWLAV&parameter1={d_id}&parameter2=CCTV"
            res = self.get_info(url)
            if not res:
                return 0
            print(self.name, res)

        # 创建多线程获取id
        lock = threading.RLock()
        vido_id = []
        for i in range(1, 3):
            t = threading.Thread(target=get_id, args=(i, vido_id))
            t.start()
            t.join()

        # 创建多线程发送请求
        for i in range(11):
            if not vido_id:
                print("id获取失败")
                return 0
            did = random.choice(vido_id)
            t = threading.Thread(target=send, args=(did,))
            t.start()
            t.join()

    # ============================== 文章(5) =================================================
    def article(self):
        # 获取文章ID
        art_id = []
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/news/content/list?channel=3&offset={1}&limit=10"
        res = self.get_info(url)
        if not res:
            return 0
        for tdict in res["result"]["articleList"]:
            art_id.append(tdict["articleId"])

        def send(d_id):
            url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/home/taskScord/completeTask?taskCode=CTWLREADARTICLE&parameter1={d_id}&parameter2=XFZX"
            res = self.get_info(url)
            if not res:
                return 0
            print(self.name, res)

        for i in range(6):
            did = random.choice(art_id)
            t = threading.Thread(target=send, args=(did,))
            t.start()
            t.join()

    # ============================== 音频(60) =================================================
    def audio(self):
        # 多线程获取视频ID
        def get_id(number, data_ls):
            ls = []
            url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/news/content/list?channel=8&offset={number}&limit=10"
            res = self.get_info(url)
            if not res:
                return 0
            for tdict in res["result"]["videoList"]:
                ls.append(tdict["videoId"])
            lock.acquire()
            data_ls += ls
            lock.release()

        # 多线程发送请求
        def send(d_id):
            url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/home/taskScord/completeTask?taskCode=CTWLAVTIME&parameter1={d_id}&parameter2=XFYP"
            res = self.get_info(url)
            if not res:
                return 0
            print(self.name, res)

        # 创建多线程获取id
        lock = threading.RLock()
        aud_id = []
        for i in range(1, 4):
            t = threading.Thread(target=get_id, args=(i, aud_id))
            t.start()
            t.join()
        # print(vido_id)

        # 创建多线程发送请求
        for i in range(21):
            if not aud_id:
                print("id获取失败")
                break
            did = random.choice(aud_id)
            t = threading.Thread(target=send, args=(did,))
            t.start()
            t.join()

    # ============================== 每日答题(5) =================================================
    def everyday(self):
        # 获取题号

        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/randomExam/0/10048/-1/10048"
        if not self.get_info(url):
            return 0
        ls = []
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/loadExamPaper/10048/10048"
        res = self.post_info(url, {})
        if not res:
            return 0
        res = res["result"]["questions"]
        for tdict in res["single"]:
            questionId = tdict["questionId"]
            checkOption = tdict["url"][:-1]
            ls.append({"questionId": questionId, "status": 0, "checkOption": checkOption})
        duoxuan = res["mutil"][0]
        questionId = duoxuan["questionId"]
        checkOption = duoxuan["url"][0:-1]
        ls.append({"questionId": questionId, "status": 0, "checkOption": checkOption})
        panduan = res["judge"][0]
        questionId = panduan["questionId"]
        context = panduan["url"]
        ls.append({"questionId": questionId, "status": 0, "context": context})
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/saveOrSubmitPaperQuestion/10048/10048/-1/submit"
        if not self.post_info(url, ls):
            return 0
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/home/taskScord/completeTask?taskCode=CTWLPRACTICEDAY"
        res = self.get_info(url)
        if not res:
            return 0
        print(self.name, res)

    # ============================== 挑战答题(5) =================================================
    def challenge(self):
        ls = []
        data = {"userAnswer": ls}
        # 获取题目
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/question/challenge"
        res = self.post_info(url, data)
        if not res:
            return 0
        for tdict in res["result"]:
            questionId = tdict["questionId"]
            for ls_dict in tdict["optionList"]:
                if ls_dict["isRight"] == "T":
                    userAnswer = ls_dict["id"]
                    ls.append({"questionId": questionId, "userAnswer": userAnswer, "type": 1})
                    break
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/question/challenge/submit"
        res = self.post_info(url, data)
        if not res:
            return 0
        print(self.name, res)

    # ============================== 我要考试(5) =================================================
    def examination(self):
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/users/checkTask?taskCode=CTWLAVTIME,CTWLAV"
        if not self.get_info(url):
            return 0
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/examTotalQuestion"
        if not self.get_info(url):
            return 0
        ls = []
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/loadExamPaper/9999/9999"
        res = self.post_info(url, {})
        if not res:
            return 0
        res = res["result"]["questions"]["single"]
        for tdict in res:
            questionId = tdict["questionId"]
            checkOption = tdict["url"][:-1]
            ls.append({"questionId": questionId, "status": 0, "checkOption": checkOption})
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/saveOrSubmitPaperQuestion/9999/9999/-1/submit"
        if not self.post_info(url, ls):
            return 0
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/home/taskScord/completeTask?taskCode=CTWLTEST"
        res = self.get_info(url)
        if not res:
            return 0
        print(self.name, res)

    # ============================== 双人对战(4) =================================================
    def pk(self):
        def send():
            ls = []
            data = {"userAnswer": ls}
            url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/question/pk"
            res = self.post_info(url, data)
            if not res:
                return 0
            res = res["result"]["list"]
            for tdict in res:
                questionId = tdict["questionId"]
                for ls_dict in tdict["optionList"]:
                    if ls_dict["isRight"] == "T":
                        userAnswer = ls_dict["id"]
                        ls.append({"questionId": questionId, "userAnswer": userAnswer, "type": 1})
                        break
            data["status"] = 1
            url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/question/pk/submit"
            res = self.post_info(url, data)
            if not res:
                return 0
            print(self.name, res)

        for _ in range(3):
            t = threading.Thread(target=send)
            t.start()
            t.join()

    # ============================== 每周答题(5) =================================================
    def weekly(self):
        # 获取题号
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/randomExam/0/10049/-1/10049"
        if not self.get_info(url):
            return 0
        ls = []
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/loadExamPaper/10049/10049"
        res = self.post_info(url, {})
        if not res:
            return 0
        res = res["result"]["questions"]
        for tdict in res["single"]:
            questionId = tdict["questionId"]
            checkOption = tdict["url"][:-1]
            ls.append({"questionId": questionId, "status": 0, "checkOption": checkOption})
        duoxuan = res["mutil"][0]
        questionId = duoxuan["questionId"]
        checkOption = duoxuan["url"][:-1]
        ls.append({"questionId": questionId, "status": 0, "checkOption": checkOption})
        panduan = res["judge"][0]
        questionId = panduan["questionId"]
        context = panduan["url"]
        ls.append({"questionId": questionId, "status": 0, "context": context})
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/course/exam/saveOrSubmitPaperQuestion/10049/10049/-1/submit"
        if not self.post_info(url, ls):
            return 0
        url = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/home/taskScord/completeTask?taskCode=CTWLPRACTICEWEEK"
        res = self.get_info(url)
        if not res:
            return 0
        print(res)

    # ============================== 执行所有任务 =================================================
    def t_all(self):
        self.audio()
        self.vido()
        self.article()
        self.everyday()
        self.challenge()
        self.examination()
        self.pk()
        self.weekly()

    # ============================== 获取用户 =================================================
    def user(self):
        us = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/users"
        res = self.get_info(us)
        if not res:
            return False
        yn = res.get("msg", "")
        if yn != "succ":
            return False
        name = res["result"]["nickName"]
        return name

    # ============================== 查看分数 =================================================
    def get_fen(self):
        integral = f"https://qmxfxx.119.gov.cn/{self.shebe}/mini/api/users/activeScore"
        fens = requests.get(url=integral, headers=self.headers, verify=False).json()["result"]
        return fens


# ============================== main ===================================================
if __name__ == '__main__':
    Authorization = [
        "bearereyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyVHlwZSI6IjQwMDAwIiwidW5pcXVlTmFtZSI6IjYzMzI5OTU3Iiwid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NDZ9.xiA0Qk26zivgPrn-WzREQ4VU-oD0b-2X1DYmVKgaLmI",
    ]


    def test(auth):
        shebe = "zhifubao"
        if shebe == "weixin":
            shebe = "wechat"
        elif shebe == "zhifubao":
            shebe = "alipay"
        qmxf = Qmxfxx(auth,shebe)
        start = qmxf.get_fen()
        # qmxf.vido()
        # qmxf.article()
        # qmxf.audio()
        # qmxf.everyday()
        # qmxf.challenge()
        # qmxf.examination()
        # qmxf.pk()
        # qmxf.weekly()
        qmxf.t_all()
        print(f"{qmxf.name}获得{qmxf.get_fen() - start}积分")


    for i in Authorization:
        t = threading.Thread(target=test, args=(i,))
        t.start()
    print("ok")
